package com.wjy.config.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.wjy.config.properties.OrderProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.SimpleTimeZone;

@RestController
@RequestMapping("/demo")
@RefreshScope
public class DemoController {

    @Autowired
    private OrderProperties orderProperties;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 测试 @ConfigurationProperties 注解的配置属性类
     */
    @GetMapping("/test01")
    public OrderProperties test01() {
        return orderProperties;
    }

    @Value(value = "${order.pay-timeout-seconds}") // @NacosValue(value = "${order.pay-timeout-seconds}")
    private Integer payTimeoutSeconds;
    @Value(value = "${order.create-frequency-seconds}") // @NacosValue(value = "${order.create-frequency-seconds}")
    private Integer createFrequencySeconds;

    /**
     * 测试 @Value 注解的属性
     */
    @GetMapping("/test02")
    public ObjectNode test02() {
        objectMapper
                // 自动加载 classpath 中所有 Jackson Module
                .findAndRegisterModules()
                // 时区序列化为 +08:00 形式
                .configure(SerializationFeature.WRITE_DATES_WITH_ZONE_ID, false)
                // 日期、时间序列化为字符串
                .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
                // 持续时间序列化为字符串
                .configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false)
                // 当出现 Java 类中未知的属性时不报错，而是忽略此 JSON 字段
                .configure(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS, false)
                // 枚举类型调用 `toString` 方法进行序列化
                .configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true)
                // 设置 java.util.Date 类型序列化格式
                .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                // 设置 Jackson 使用的时区
                .setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));
        ObjectNode jsonObject = objectMapper.createObjectNode()
                .put("payTimeoutSeconds", payTimeoutSeconds)
                .put("createFrequencySeconds", createFrequencySeconds);
        return jsonObject;
    }
}
